package com.icedevcloud.common.core.log;

import cn.hutool.json.JSONUtil;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * <p>
 * LogAspect
 * </p>
 *
 * @author XiaoBingBy
 * @since 2023-04-02
 */
@Slf4j
@Aspect
@Order(1)
public class LogAspect {

    @Around(value = "@annotation(iceLog)")
    public Object redisLock(ProceedingJoinPoint point, IceLog iceLog) throws Throwable {
        String strMethodName = point.getSignature().getName();
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Operation operation = method.getAnnotation(Operation.class);

        String logPrefix;
        if (operation != null) {
            logPrefix = operation.summary();
        } else {
            logPrefix = strMethodName;
        }

        Object obj;
        try {
            if (iceLog.req()) {
                log.info("【{}】请求参数【{}】", logPrefix, JSONUtil.toJsonStr(point.getArgs()));
            }
            obj = point.proceed();
            if (iceLog.res()) {
                log.info("【{}】返回参数【{}】", logPrefix, JSONUtil.toJsonStr(obj));
            }
        } catch (Exception e) {
            throw e;
        }
        return obj;
    }

}
